package com.handong.handserialprogram.module.choosering;

import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.constants.ColorContant;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.entities.PersonEntity;
import com.handong.handserialprogram.model.status.FootRingStatus;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.ViewUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by userKey on 2017/8/13.
 */

public class ARingAdapter extends RecyclerView.Adapter<ARingAdapter.ARingHolder> {

    private static final int NORMAL_TEXT = Color.parseColor("#6198FE");
    private List<FootRingNewEntity> mFootRingList;
    private ChooseRingActivity mActivity;
    private RecyclerView mRecyclerView;
    private MaterialDialog mRouteDialog;
    private List<PersonEntity> mPersonEntityList;

    public ARingAdapter(List<PersonEntity> personEntityList,List<FootRingNewEntity> list, ChooseRingActivity activity) {
        mFootRingList = list;
        mActivity = activity;
        mPersonEntityList=personEntityList;
    }

    public void SetRingList(List<FootRingNewEntity> list)
    {
        mFootRingList=list;
    }

    @Override
    public ARingHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        mRecyclerView= (RecyclerView) parent;

        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.adapter_ring_list_item, parent, false);
        return new ARingHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ARingHolder holder, int position) {
        FootRingNewEntity entity = mFootRingList.get(position);
        holder.mHolderEntity = entity;
        holder.ringID.setText(entity.getRingID());
        holder.ringActualDistance.setText(entity.getActualRingDistance() + "m");
        holder.ringSetDistance.setText(entity.getSetRingDistance() + "m");
        if (entity.getStatus() == FootRingStatus.ESCAPE) {
            holder.ringActualDistance.setTextColor(ColorContant.PERSON_ESCAPE);
        } else {
            holder.ringActualDistance.setTextColor(NORMAL_TEXT);
        }
        if(entity.isResult()) {
            if (entity.isAudioError() || entity.isSimError() || entity.isUwbError() || entity.isWifiError() || entity.isIs4gError()) {
                holder.equipmentStatus.setEnabled(false);
                holder.mCriminalName.setVisibility(View.GONE);
                holder.ringStatus.setVisibility(View.VISIBLE);
                setBtnState(holder, R.drawable.icon_ring_sleep, "自检异常", Color.parseColor("#FF0000"), true);
            } else {
                holder.equipmentStatus.setEnabled(true);
                setBtnState(holder, R.drawable.icon_ring_working, "选择犯人", ColorContant.PERSON_NORMAL, true);
                if (entity.isMyBingding()) {

                    holder.equipmentStatus.setChecked(true);
                    if (entity.getCriminalName().equals("")) {
                        holder.mCriminalName.setVisibility(View.GONE);
                        if(holder.isAllPersonBinded()) {
                            holder.ringStatus.setVisibility(View.GONE);
                        }
                        else{
                            holder.ringStatus.setVisibility(View.VISIBLE);
                        }
                    } else {
                        holder.mCriminalName.setVisibility(View.VISIBLE);
                        holder.mCriminalName.setText(entity.getCriminalName());
                        holder.ringStatus.setVisibility(View.GONE);
                    }
                } else {
                    holder.ringStatus.setVisibility(View.VISIBLE);
                    setBtnState(holder, R.drawable.icon_ring_sleep, "自检成功", ColorContant.PERSON_NORMAL, true);
                    holder.equipmentStatus.setChecked(false);
                    holder.mCriminalName.setVisibility(View.GONE);
                    //holder.ringStatus.setVisibility(View.GONE);
                    entity.setCriminalId("");
                    entity.setCriminalName("");
                }
            }
        }
        else{
            holder.equipmentStatus.setEnabled(false);
            entity.setBingding(false);
            entity.setCriminalId("");
            entity.setCriminalName("");
            holder.equipmentStatus.setChecked(false);
            holder.mCriminalName.setVisibility(View.GONE);
            holder.ringStatus.setVisibility(View.VISIBLE);
            setBtnState(holder, R.drawable.icon_ring_sleep, "自检中" ,Color.parseColor("#C0C0C0"), false);
            //setBtnState(holder, R.drawable.icon_ring_sleep, "自检中", Color.parseColor("#FF0000"), true);
        }
    }

    private void setBtnState(ARingHolder holder, int iconID, String des, int color, boolean isEnabled){
        GradientDrawable drawable = (GradientDrawable) holder.ringStatus.getBackground();
        holder.ringIcon.setImageResource(iconID);
        if(!TextUtils.isEmpty(des))
        holder.ringStatus.setText(des);
        drawable.setColor(color);
        holder.mActivateLayout.setEnabled(isEnabled);
    }

    public View getActiveView(int posstion) {
        ARingHolder holder= (ARingHolder) mRecyclerView.findViewHolderForLayoutPosition(posstion);
        return  holder.ringStatus;
    }

    @Override
    public int getItemCount() {
        return mFootRingList == null ? 0 : mFootRingList.size();
    }

    public class ARingHolder extends RecyclerView.ViewHolder  {

        private FootRingNewEntity mHolderEntity;

        private TextView ringID, ringSetDistance, ringActualDistance, ringStatus,mCriminalName;
        private FrameLayout mActivateLayout;
        private ImageView ringIcon;
        private AppCompatCheckBox equipmentStatus;
        //private int position=0;
        //private boolean isChecked;

        public ARingHolder(View itemView) {
            super(itemView);

            ringIcon = (ImageView) itemView.findViewById(R.id.ringItemIcon);
            ringID = (TextView) itemView.findViewById(R.id.ringItemID);
            ringSetDistance = (TextView) itemView.findViewById(R.id.ringItemSetDistance);
            ringActualDistance = (TextView) itemView.findViewById(R.id.ringItemActualDistance);
            ringStatus = (TextView) itemView.findViewById(R.id.ringItemBtnSet);
            mCriminalName=(TextView) itemView.findViewById(R.id.crimanalName);
            mActivateLayout = (FrameLayout) ringStatus.getParent();
            //mActivateLayout.setOnClickListener(this);
            equipmentStatus=(AppCompatCheckBox)itemView.findViewById(R.id.choosePersonStatus);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mHolderEntity.isWifiError()||mHolderEntity.isUwbError()||mHolderEntity.isSimError()||mHolderEntity.isAudioError()||mHolderEntity.isIs4gError())
                    {

                    }
                    else {
                        if (equipmentStatus.isEnabled()) {
                            if (!mHolderEntity.isMyBingding()) {
                                //equipmentStatus.setChecked(true);
                                mHolderEntity.setMyBingding(true);
                                notifyDataSetChanged();

                            } else {
                                //equipmentStatus.setChecked(false);
                                mHolderEntity.setMyBingding(false);
                                notifyDataSetChanged();

                            }
                        }
                    }
                }
            });
            ringStatus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //getRouteSuccess(position);
                    if(mHolderEntity.isResult()) {
                        if (mHolderEntity.isWifiError() || mHolderEntity.isUwbError() || mHolderEntity.isSimError() || mHolderEntity.isAudioError() || mHolderEntity.isIs4gError()||!mHolderEntity.isMyBingding()) {
                            showCheckDialog(mHolderEntity.getRingID(), "\r\nWIFI模块:" + (mHolderEntity.isWifiError() ? "异常" : "正常") + "\r\n测距模块:" + (mHolderEntity.isUwbError() ? "异常" : "正常") + "\r\nSIM卡模块:" + (mHolderEntity.isSimError() ? "异常" : "正常") + "\r\n声音模块:" + (mHolderEntity.isAudioError() ? "异常" : "正常") + "\r\n4G模块:" + (mHolderEntity.isIs4gError() ? "异常" : "正常"));
                        } else {
                            getRouteSuccess();
                        }
                    }

                }
            });
//            ringStatus.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    if (!mHolderEntity.isMyBingding()) {
//                        //equipmentStatus.setChecked(true);
//                        mHolderEntity.setMyBingding(true);
//                    } else {
//                        //equipmentStatus.setChecked(false);
//                        mHolderEntity.setMyBingding(false);
//                    }
//                }
//            });
            //itemView.setOnClickListener(this);

        }

        /**
         * 脚环自检错误
         */
        public void showCheckDialog(final String paramString,final String errorString) {
            ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(mActivity)
                    .content("脚环"+paramString+"自检完成，详情："+errorString)
                    .negativeColorRes(R.color.dialog_bg)
                    .negativeText(R.string.dialog_negative_text)
                    .build());
        }

        /**
         * 判断当前是否所有犯人都已经被绑定
         * @return
         */
        public boolean isAllPersonBinded(){
            int bindedPersonCount=0;
            for (FootRingNewEntity entity:
                 mFootRingList) {
                String code = entity.getCriminalId();
                if (!TextUtils.isEmpty(code)){
                    bindedPersonCount++;
                }
            }
            return bindedPersonCount==mPersonEntityList.size();

        }

        /**
         * 录入线路成功
         */
        public void getRouteSuccess() {
            ArrayList<PersonEntity> nPersonList=new ArrayList<PersonEntity>();
            nPersonList.addAll(mPersonEntityList);
            for (FootRingNewEntity entity:
                 mFootRingList) {
                if (entity!=mHolderEntity) {
                    String code = entity.getCriminalId();
                    PersonEntity hasPersonEntity = null;
                    for (PersonEntity personEntity :
                            mPersonEntityList) {
                        if (!TextUtils.isEmpty(code) && personEntity.getId().equals(code)) {
                            hasPersonEntity = personEntity;
                        }
                    }
                    if (hasPersonEntity != null) {
                        nPersonList.remove(hasPersonEntity);
                    }
                }
            }
            int len =nPersonList.size();
            String[] itemName = new String[len];
            String[] itemCode = new String[len];
            int checked = -1;
            String code = mHolderEntity.getCriminalId();
            PersonEntity entity = null;
            for (int i = 0; i < len; i++) {
                entity = nPersonList.get(i);
                itemName[i] = entity.getName();
                itemCode[i] = entity.getId();
                if (!TextUtils.isEmpty(code) && entity.getId().equals(code)) {
                    checked = i;
                }
            }
            if (mRouteDialog!=null)
            {
                mRouteDialog.dismiss();
            }

            mActivity.dismissLoadingDialog();
            showRouteDialog(itemName, itemCode, checked);
        }

        /**
         * 选择线路
         */
        private void showRouteDialog(String[] nameArr, final String[] codeArr, int checked) {

            //if (mRouteDialog == null) {
            mRouteDialog = new MaterialDialog.Builder(mActivity)
                    .title("选择犯人")
                    .items(nameArr)
                    .canceledOnTouchOutside(false)
                    .widgetColorRes(R.color.colorPrimary)
                    .itemsCallbackSingleChoice(checked, new MaterialDialog.ListCallbackSingleChoice() {
                        @Override
                        public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                            if (-1 == which) {
                                return true;
                            }
                            mHolderEntity.setCriminalId(codeArr[which]);
                            mHolderEntity.setCriminalName(text.toString());
                            notifyDataSetChanged();
                            return true;
                        }
                    })
                    .positiveColorRes(R.color.back_ground_green)
                    .positiveText(R.string.dialog_positive_text)
                    .negativeColorRes(R.color.bg_gray)
                    .negativeText(R.string.dialog_negative_text)
                    .neutralColorRes(R.color.login_warning_bg_color)
//                    .neutralText(R.string.option_item_reset)
//                    .onNeutral(new MaterialDialog.SingleButtonCallback() {
//                        @Override
//                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                            mFootRingList.get(position).setCriminalId("");
//                            mFootRingList.get(position).setCriminalName("");
//                            dialog.setSelectedIndex(-1);
//                        }
//                    })
                    .build();
            //}
            ViewUtil.removeHomeKeyListener(mRouteDialog);
        }



//        @Override
//        public void onClick(View v) {
//            switch (v.getId()) {
//                case R.id.ringItemBtnSetLayout:
//                    if (mHolderEntity.getStatus() == FootRingStatus.ESCAPE) {
//                        AppUtil.showShortToast(mFragment.getContext(), "无法检测到脚环");
//                        return;
//                    }
//
//                    if (!mHolderEntity.isNormalWork()) {
//
//                        mFragment.activateFootRing(mHolderEntity.getRingID());
//                    } else {
//                        mFragment.showExitDialog(mHolderEntity.getRingID());
//                    }
//                    break;
//
//                case R.id.ringItemContainer:
////                    if (!mHolderEntity.isNormalWork()) {
////                        mActivity.showActivateGuideView(ringStatus, R.id.ringItemBtnSet);
////                        return;
////                    }
////                    mActivity.uploadPersonBindInfo(mHolderEntity);
//                    break;
//            }
//        }

    }
}
